import pandas as pd
import matplotlib.pyplot as plt

# 配置 matplotlib 支持中文显示
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

# 配置常量
FILE_PATH = 'd:/民大实训/git-mcp-test/project/FhjlViewDD.xlsx'
DATE_COLUMN = '创建时间'
MINERAL_COLUMN = '净重'
OUTPUT_IMAGE = 'd:/民大实训/git-mcp-test/project/june_mineral_total.png'

# 封装数据处理函数
def load_and_process_data():
    # 读取 Excel 文件
    df = pd.read_excel(FILE_PATH)
    df[DATE_COLUMN] = pd.to_datetime(df[DATE_COLUMN])
    # 筛选 6 月份的数据
    june_data = df[df[DATE_COLUMN].dt.month == 6]
    # 按日期分组并计算每日矿粉总量
    daily_total = june_data.groupby(june_data[DATE_COLUMN].dt.day)[MINERAL_COLUMN].sum()
    return daily_total

# 封装绘图函数
def plot_and_save_data(daily_total):
    # 设置图片清晰度
    plt.rcParams['figure.dpi'] = 300
    # 绘制统计图
    plt.figure(figsize=(12, 6))
    ax = daily_total.plot(kind='bar')
    plt.title('6 月份每日矿粉总量统计图')
    plt.xlabel('日期（日）')
    plt.xticks(rotation=0)
    plt.ylabel('矿粉总量')
    plt.grid(True)
    # 添加数据标签
    for p in ax.patches:
        ax.annotate(format(p.get_height(), '.0f'),
                    (p.get_x() + p.get_width() / 2., p.get_height()),
                    ha = 'center', va = 'center',
                    xytext = (0, 9),
                    textcoords = 'offset points')
    plt.tight_layout()
    # 保存图片
    plt.savefig(OUTPUT_IMAGE)
    plt.close()

if __name__ == '__main__':
    try:
        daily_total = load_and_process_data()
        plot_and_save_data(daily_total)
        print('6 月份每日矿粉总量统计完成，统计图已保存至 june_mineral_total.png')
    except Exception as e:
        print(f'处理过程中出现错误: {e}')